require "digest/sha1"

class User < ActiveRecord::Base
  
  validates_format_of :email, :with => %r{^[a-z0-9_.-]+@[a-z0-9_.-]+\.[a-z]+$}i, :message => ": Keine gültige e-Mail-Adresse."
  validates_presence_of :vorname, :nachname, :str, :plz_ort, :tel, :message => ": Bitte angeben."
  validates_uniqueness_of :email, :message => ": Sie haben sich mit dieser Adresse bereits angemeldet."
  
  attr_accessor :plain_password

  def before_create
    self.salt = User.hash_string(User.random_readable_string)
    @plain_password = User.random_readable_string
    self.password = User.hash_string(self.salt + @plain_password)
  end

  def try_login
    user = User.find_first(["email = ?", self.email])
    return nil if user.nil?
    hashed_password = User.hash_string(user.salt + self.password)
    user = User.find_first(["email = :email and (password = :hp or password_new = :hp)",
                        { :email => self.email, :hp => hashed_password } ])
    return nil if user.nil?
    user.password = user.password_new if user.password_new == hashed_password
    user.password_new = ''
    user.save
    return user
  end
  
  def regenerate_password
    users = User.find_all(["email = ?", self.email])
    return nil if users.length == 0
    users.each do |user|
      user.plain_password = User.random_readable_string
      user.password_new = User.hash_string(user.salt + user.plain_password)
      user.save
    end
    return users
  end
  
  def self.random_readable_string(length = 8)
    v = 'aeiou'
    k = 'bcdfghklmnpqrstvwxz'
  	string = String.new
  	odd_or_even = 0
  	length.times do
  	  odd_or_even = 1 - odd_or_even
  	  if odd_or_even == 1
  	    string << k[Kernel.rand(k.length)]
	    else
	      string << v[Kernel.rand(v.length)]
      end
  	end
  	return string
  end
  
  def self.hash_string(string)
    Digest::SHA1.hexdigest(string)
  end
end